package com.tangzhe.demo07.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 测试：
 * 拦截器
 * 上传文件
 * 下载文件
 */
@Controller
@RequestMapping("demo07")
public class Demo07Controller {

    /**
     * 测试拦截器
     */
    @RequestMapping("/test")
    public String testInterceptor() {
        return "demo07";
    }

    /**
     * 测试文件上传
     */
    @RequestMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        //获取文件原始名称
        String name = file.getOriginalFilename();

        //创建文件
        File uploadFile = new File("/" + name);

        //上传
        file.transferTo(uploadFile);

        return "demo07";
    }

    /**
     * 测试下载文件
     */
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download() throws IOException {
        //所要下载的文件路径
        String path = "F:\\pic\\timg.jpg";

        //创建文件对象
        File file = new File(path);

        //创建http请求头对象
        HttpHeaders headers = new HttpHeaders();

        //设置文件名，解决中文乱码问题
        String fileName = new String("测试.jpg".getBytes("utf-8"), "iso8859-1");

        //设置附件
        headers.setContentDispositionFormData("attachment", fileName);

        //设置文件类型
        headers.setContentType(MediaType.IMAGE_JPEG);

        //返回ResponseEntity对象
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

}
